package viz.model.flare.decoders
{
	import viz.model.IDecodeable;


	public class XML2StateMap implements IDecodeable
	{
		
		
		private var o:Object;
		
		public function XML2StateMap( o:Object ):void{
			this.o = o;
		}
		
		public function decode(  ):Object{
			var a:Array = decodeStates( XML( o ));
			return  new Untyped2StateMap( a ).decode( );
		}
		
		private function decodeStates( xml:XML ):Array{
			var list:XMLList = xml.state,
				a:Array = [],
				o:Object;
			
			for each(var state:XML in list){
				o = {}
				o.fullPath = "root."+stripOutName( state.@name );
				
				if(state.@entering.toString() == ""){
					o.entering = false;
				}else{
					o.entering = true;
				}
				if(state.@exiting.toString() == ""){
					o.exiting = false;
				}else{
					o.exiting = true;
				}
				if(state.@changed.toString() == ""){
					o.changed = false;
				}else{
					o.changed = true;
				}
				
				o.targets = decodeTargets( state.transition );
				a.push(o);
			}	
			
			markInitial(a, "root."+stripOutName( xml.@initial ))
			
			return a;
		}
		
		private function markInitial( a:Array, fullPath:String):void{
			for each (var o:Object in a ){
				if(o.fullPath == fullPath){
					o.initial = true;
					return;
				}
			}
		}
		private function decodeTargets( list:XMLList ):Array{
			var a:Array = [],
				o:Object;
			
			for each(var action:XML in list){
				o = {};
				o.name = stripOutName( action.@action );
				o.target = "root."+stripOutName( action.@target );
				a.push(o);
			}	
			
			return a;
		}
		
		private function stripOutName(s:String):String{
			var split:Array = s.split("/");
			return split[split.length-1]
		}
		
		
	
	}
}